package com.eddie.juc.cf;

import com.eddie.juc.IThreadPool;
import lombok.SneakyThrows;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author Eddie
 * @date 2022/08/17 16:01
 **/
public class CompletableFutureUseDemo {
    private static final IThreadPool THREAD_POOL = IThreadPool.getInstance();

    @SneakyThrows
    public static void main(String[] args) {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "----come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //设置错误，校验异常处理
            int i = 10/0;
            System.out.println("---------1秒钟后出结果：" + result);
            return result;
        }, THREAD_POOL);
        //v -> 上一步的结果->返回值；e->异常
        completableFuture.whenComplete((v, e) -> {
            if (e == null) {
                System.out.println("计算完成，更新系统UpdateVa：" + v);
            }
            //异常情况
        }).exceptionally(throwable -> {
            throwable.printStackTrace();
            System.out.println("异常情况：" + throwable.getCause() + "\t" + throwable.getMessage());
            return null;
        });
        System.out.println(Thread.currentThread().getName() + "线程先去忙其他任务");

        //注意事项：重点！！！如果不设置自定义线程池则默认为FokeJoinPool.commonPool()，而该线程池是一个守护线程
        //当main主线程结束后，守护线程也结束了，整个jvm虚拟机就关闭了

        THREAD_POOL.shutdown();
    }

    private static void future1() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "----come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("---------1秒钟后出结果：" + result);
            return result;
        }, THREAD_POOL);
        System.out.println(Thread.currentThread().getName() + "线程先去忙其他任务");
        System.out.println(completableFuture.get());
    }
}
